<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card v-loading="loading">
        <el-tabs v-model="activeName">

          <!-- 左侧 -->
          <el-tab-pane label="用户管理" name="first">
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="addRole"
            >新增角色</el-button>
            <el-table
              :data="tableData"
              style="width: 100%"
            >
              <el-table-column
                type="index"
                label="序号"
                width="100"
                :index="indexMethod"
              />
              <el-table-column
                prop="name"
                label="角色名称"
                width="240"
              />
              <el-table-column
                prop="description"
                label="描述"
              />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="clickShowAssignDialog(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="deRole(row.id)">删除</el-button>
                </template>

              </el-table-column>
            </el-table>
            <el-pagination
              :current-page="page"
              :page-sizes="[1, 2, 3,4,5]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>

          <!-- 右侧 -->
          <el-tab-pane label="公司信息" name="second">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>

        </el-tabs>
      </el-card>

      <el-dialog title="弹层标题" :visible="showDialog" @close="closeDialog">
        <el-form ref="roleform" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name" placeholder="请输入角色名称">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" placeholder="请输入角色名称" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button type="primary" @click="submitBtn">确认</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </template>
      </el-dialog>

      <el-dialog title="分配权限" :visible="showAssignDialog" @close="closeAssignDialog" @open="openAssignDialog">
        <el-tree
          ref="tree"
          v-loading="treeLoading"
          node-key="id"
          :data="permissionData"
          :props="{ label: 'name' }"
          :default-expand-all="true"
          :show-checkbox="true"
          :check-strictly="true"
        />
        <template #footer>
          <div style="text-align:right">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="cliclAssign">确定</el-button>

          </div>
        </template>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import { reqGetRoleList, reqDeleteRole, reqAddRole, reqGetRoleDetail, reqUpdaRole, reqAssignPerm } from '@/api/setting'
import { reqGetPermissionList } from '@/api/permisson'
import { reqGetCompanyById } from '@/api/company'
import { tranListToTreeData } from '@/utils'
import { mapState } from 'vuex'
export default {
  name: 'Setting',
  data() {
    return {
      treeLoading: false,
      activeName: 'first',
      tableData: [],
      page: 1, // 当前页
      pagesize: 2, // 每页条数
      total: 0, // 总条数\
      loading: false,
      showDialog: false,
      roleId: '',
      permissionData: [], // 存储权限数据
      form: {
        name: '',
        description: ''
      },
      companyForm: {

      },
      showAssignDialog: false,
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: ['blur', 'change'] }
        ]
      }

    }
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    async getRoleList() {
      this.loading = true
      const { data: { rows, total }} = await reqGetRoleList(this.page, this.pagesize)
      this.total = total
      this.tableData = rows
      this.loading = false
    },
    async getCompanyInfo() {
      const { data } = await reqGetCompanyById(this.userInfo.companyId)
      this.companyForm = data
    },

    handleSizeChange(val) {
      this.pagesize = val
      this.page = 1
      this.getRoleList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getRoleList()
    },

    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },

    async deRole(id) {
      this.$confirm('将删除该角色？是否继续', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        // 删除操作成功
        const res = await reqDeleteRole(id)
        if (this.tableData.length === 1 && this.page > 1) {
          this.page--
        }
        this.getRoleList()
        this.$message.success('删除角色成功')
        console.log(res)
      }).catch(err => {
        console.log(err)
      })
    },

    closeDialog() {
      this.showDialog = false
      this.form = {
        name: '',
        description: ''
      }
      this.$refs.roleform.resetFields()
    },

    addRole() {
      this.showDialog = true
    },

    submitBtn() {
      this.$refs.roleform.validate(async flag => {
        if (!flag) return
        if (this.form.id) {
          // 进行编辑操作
          const res = await reqUpdaRole(this.form)
          console.log(res)
        } else {
          // 添加操作
          const res = await reqAddRole(this.form)
          console.log(res)
        }

        this.closeDialog()
        this.getRoleList()
        this.$message.success('操作成功')
      })
    },

    async showEdit(id) {
      const { data } = await reqGetRoleDetail(id)
      this.form = data
      this.showDialog = true
    },

    editRole(id) {
      this.showEdit(id)
    },

    closeAssignDialog() {
      this.showAssignDialog = false
    },

    clickShowAssignDialog(id) {
      this.roleId = id
      this.showAssignDialog = true
    },

    async openAssignDialog() {
      this.treeLoading = true
      const { data } = await reqGetPermissionList()
      this.permissionData = tranListToTreeData(data, '0')
      const { data: roleDetail } = await reqGetRoleDetail(this.roleId)
      this.$refs.tree.setCheckedKeys(roleDetail.permIds)
      console.log(this.permissionData, roleDetail.permIds, 111)
      this.treeLoading = false
    },

    async cliclAssign() {
      const res = await reqAssignPerm({
        id: this.roleId,
        permIds: this.$refs.tree.getCheckedKeys()
      })
      console.log(res)
      this.$message.success('分配成功')
      this.showAssignDialog = false
    }

  },
  // eslint-disable-next-line vue/order-in-components
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  }
}
</script>

<style>

</style>
